#!/usr/bin/env python 3.6
# -*- coding: utf-8 -*-
# @Time      :2019/4/9
# @Author    :Tian Maohong
# @Email     :tianmaohong@bbdservice.com
# @File      :R32_EC_PaidLoanConditionsAndPaidAttentionCheck
# @Software  :PyCharm


'''eof
name:申请企业已结清业务中借贷交易条件外关注校验
code:R32_EC_PaidLoanConditionsAndPaidAttentionCheck_2D
tableName:
columnName:
groups:企业征信校验
dependencies:EC_DSJ_2D
type:常用指标
datasourceType:在线指标
description:
eof'''

import json
import re
import sys
import datetime
import pandas as pd


reload(sys)
sys.setdefaultencoding('utf-8')

# 加入 [] 判断
null_type_list = ['', ' ', None, 'null', 'Null', 'NULL', '/', '-', '--', []]

def formatData(table_Name):
    """
    获取数据
    :param table_Name:字典keys
    :return:[{}]
    """
    try:
        data = EC_DSJ_2D["data"].get(table_Name)
        # table 不存在
        if data is None:
            return None
        # 表存在 但是为空[]
        elif data == "" or (isinstance(data, list) and len(data) == 0):
            return [{}]
        else:
            return data
    except:
        return None

def isFloat(x):
    '''
    判断x为float类型且大于等于0
    :param x:
    :return:
    '''
    try:
        if isinstance(float(x), float) and float(x) >= 0:
            if str(x) in ['inf', 'infinity', 'INF', 'INFINITY', 'True']:
                return False
            else:
                return True
        else:
            return False
    except:
        return False


def convertDataType(data_value, data_type):
    """
    数据格式转换
    :param data_value:
    :param data_type: float/int/str/date_time
    :return:
    """

    return_data = None
    data_value = str(data_value)
    # float
    if data_type == 'float':
        try:
            return_data = float(data_value) if len(data_value) >= 0 else None
        except:
            return_data = None
    # int
    elif data_type == 'int':
        try:
            return_data = int(data_value) if len(data_value) >= 0 else None
        except:
            return_data = None
    # str
    elif data_type == 'str':
        try:
            return_data = str(data_value) if len(data_value) >= 0 else None
        except:
            return_data = None
    # date_time
    elif data_type == 'date_time':
        r = re.compile(r'\D+')
        try:
            return_data = datetime.datetime.strptime(data_value, '%Y.%m.%d')
        except:
            try:
                return_data = datetime.datetime.strptime(data_value, '%Y-%m-%d')
            except:
                try:
                    return_data = datetime.datetime.strptime(data_value, '%Y/%m/%d')
                except:
                    try:
                        data_value = r.sub('', data_value)
                        return_data = datetime.datetime.strptime(data_value, '%Y%m%d')
                    except:
                        return_data = None

    return return_data

def dateFormat(time):
    import re
    import datetime
    r = re.compile(r'\D+')
    try:
        date = datetime.datetime.strptime(time, '%Y.%m.%d')
    except:
        try:
            date = datetime.datetime.strptime(time, '%Y-%m-%d')
        except:
            try:
                date = datetime.datetime.strptime(time, '%Y/%m/%d')
            except:
                try:
                    tmp = r.sub('', time)
                    date = datetime.datetime.strptime(tmp, '%Y%m%d')
                except:
                    date = None
    return date

def R32_EC_PaidLoanConditionsAndPaidAttentionCheck():
    """
    "Factor=统计借贷账户信息单元·基本信息段(ED01A)·账户活动状态(ED01AD01)==2(已结清)and 业务类型(不存在该字段)借贷业务种类
    大类(ED01AD05)不为“21”(票据贴现)&还款表现信息段(ED01B)·五级分类（ED01BD01）==“2(关注)”and ((最近一次实际还款日期(ED01BR04)-最近一次约定还款日期(ED01BR05)>7 or最近一次还款形式(ED01BD02)∉（10（正常还款）,22(政策性还款)))的笔数。

    如""最近一次实际还款日期""或""最近一次约定还款日期""为空，则返回缺失值"

    :return:
    """
    EAA = formatData('EAA')#报告头
    #如果没有报告头直接通过
    if EAA in null_type_list or EAA == [{}]:
        fiveyearsago = 0
    else:
        EA01 = EAA[0].get('EA01')
        if EA01 is None or EA01 in null_type_list:
            fiveyearsago =0
        else:
            EA01A=EA01[0].get("EA01A")
            if EA01A is None or EA01A in null_type_list:
                fiveyearsago =0
            else:
                try:
                    #报告生成日期
                    EA01AR01 = EA01A[0].get('EA01AR01')
                    create_date=datetime.datetime.strptime(EA01AR01[0:10], '%Y-%m-%d')
                    fiveyearsago= (create_date- pd.tseries.offsets.DateOffset(years=5)).strftime("%Y%m%d")
                except:
                    fiveyearsago = 0

    EDA = formatData("EDA")             # 借贷账户信息

    if EDA is None:
        return u'缺失值'
    elif EDA == [{}]:
        return 0
    else:
        #ED01  [0..*]
        ED01 = EDA[0].get("ED01")
        # 不存在 0条
        if ED01 is None:
            return 0
        # 存在 但是异常
        elif ED01 in null_type_list:
            return u'缺失值'
        else:
            Factor = []
            for i in range(len(ED01)):
                ED01A = ED01[i].get("ED01A")
                ED01B = ED01[i].get("ED01B")

                if ED01A is None or ED01B is None:
                    Factor.append(None)
                elif ED01B == "":
                    Factor.append(0)
                else:
                    ED01AD01 = ED01A[0].get("ED01AD01")     # 账户活动状态   账户活动状态(ED01AD01)==2(已结清)
                    ED01AD05 = ED01A[0].get("ED01AD05")     # 借贷业务大类   借贷业务种类大类()不为“21”(票据贴现)
                    ED01AR02 = ED01A[0].get("ED01AR02")  # 到期日期
                    ED01BH = ED01B[0].get("ED01BH")  # 还款表现信息

                    if ED01AD01 in null_type_list or ED01AD05 in null_type_list or ED01AR02 in null_type_list:
                        Factor.append(None)
                    else:
                        if convertDataType(ED01AD01, 'str') == '2' and convertDataType(ED01AD05, 'str') != '21':
                            if ED01BH is None:
                                Factor.append(0)
                            elif ED01BH in null_type_list or len(ED01BH) == 0:
                                Factor.append(None)
                                continue
                            else:
                                ED01BR01_latest, ED01BD01_latest, ED01BR04_latest, ED01BD02_latest = "", "", "", ""
                                for j in range(len(ED01BH)):
                                    ED01BR01 = ED01BH[j].get("ED01BR01") # 信息报告日期
                                    ED01BD01 = ED01BH[j].get("ED01BD01")  # 五级分类   五级分类（ED01BD01）==“2(关注)
                                    ED01BR04 = ED01BH[j].get("ED01BR04")  # 最近一次实际还款日期
                                    ED01BD02 = ED01BH[j].get("ED01BD02")  # 最近一次还款形式
                                    if j == 0:
                                        ED01BR01_latest = ED01BR01
                                        ED01BD01_latest = ED01BD01
                                        ED01BR04_latest = ED01BR04
                                        ED01BD02_latest = ED01BD02
                                    else:
                                        if ED01BR01_latest < ED01BR01:
                                            ED01BR01_latest = ED01BR01
                                            ED01BD01_latest = ED01BD01
                                            ED01BR04_latest = ED01BR04
                                            ED01BD02_latest = ED01BD02
                                            try:
                                                #信息报告日期
                                                ED01BR01_latest=dateFormat(ED01BR01_latest)
                                                #ED01BR01_latest=ED01BR01_latest.strftime("%Y%m%d")
                                            except:
                                                ED01BR01_latest = 0
                                        if ED01BD01_latest in null_type_list:
                                            Factor.append(None)
                                            continue

                                if (convertDataType(ED01BD01_latest, 'str') == '2'):
                                    ED01BR01_latest=dateFormat(ED01BR01_latest)
                                    if ED01AR02 not in null_type_list:
                                        if (convertDataType(ED01BR04_latest, 'date_time') in null_type_list) or convertDataType(ED01AR02,'date_time') in null_type_list:
                                            if (convertDataType(ED01BD02_latest, 'str') in null_type_list):
                                                Factor.append(None)
                                                continue
                                            else:
                                                if convertDataType(ED01BD02_latest, 'str') not in ['10', '22']:
                                                    if fiveyearsago == 0 or ED01BR01_latest == 0:
                                                        Factor.append(1)
                                                    elif ED01BR01_latest.strftime("%Y%m%d") >= fiveyearsago:
                                                        Factor.append(1)
                                                    else:
                                                        Factor.append(0)
                                                else:
                                                    Factor.append(0)
                                        else:
                                            if convertDataType(ED01BR04_latest, 'date_time').date() - convertDataType( ED01AR02, 'date_time').date() > datetime.timedelta(7):
                                                if fiveyearsago == 0 or ED01BR01_latest == 0:
                                                    Factor.append(1)
                                                elif ED01BR01_latest.strftime("%Y%m%d") >= fiveyearsago:
                                                    Factor.append(1)
                                                else:
                                                    Factor.append(0)
                                            elif convertDataType(ED01BD02_latest, 'str') not in null_type_list and convertDataType( ED01BD02_latest, 'str') not in ['10', '22']:
                                                if fiveyearsago == 0 or ED01BR01_latest == 0:
                                                    Factor.append(1)
                                                elif ED01BR01_latest.strftime("%Y%m%d") >= fiveyearsago:
                                                    Factor.append(1)
                                                else:
                                                    Factor.append(0)
                                            elif convertDataType(ED01BD02_latest, 'str') in null_type_list:
                                                Factor.append(None)
                                                continue
                                            else:
                                                Factor.append(0)
                                    # 到期日期为空，直接拒绝
                                    else:
                                        Factor.append(None)
                                else:
                                    Factor.append(0)
                        else:
                            Factor.append(0)
            if "None" in Factor:
                return u'缺失值'
            Factor = filter(lambda x:x is not None, Factor)
            if len(Factor) == 0:
                return u'缺失值'
            else:
                return sum(Factor)


result = R32_EC_PaidLoanConditionsAndPaidAttentionCheck()

